package org.csy.work.dao.impl;

import org.csy.work.dao.UsersDao;
import org.csy.work.entity.Users;
import org.csy.work.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author CSY
 * @date 2024-11-26
 */
public class UsersDaoImpl implements UsersDao {
    @Override
    public Users login(String username) {
        Users user = null;
        String sql = "select id,username,password,email,phone,image,register_time,level,status" +
                " from users where username=?";
        Connection conn = DbUtil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if(rs.next()) {
                user = new Users();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setImage(rs.getString("image"));
                user.setRegisterTime(rs.getDate("register_time"));
                user.setLevel(rs.getString("level"));
                user.setStatus(rs.getInt("status"));
            }
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DbUtil.close(rs, ps, conn);
        }

        return user;
    }

    @Override
    public int register(Users user) {
        int n = 0;
        String sql = "insert into users(username,password,phone,email) values (?,?,?,?)";
        Connection conn = DbUtil.getConnection();
        PreparedStatement ps = null;
        try {
            ps= conn.prepareStatement(sql);
            String md5Pwd = DbUtil.MD5(user.getPassword());
            ps.setString(1, user.getUsername());
            ps.setString(2,md5Pwd);
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getEmail());
            n = ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DbUtil.close(null, ps, conn);
        }
        return n;
    }
}
